package jnpf.service.impl;

import jnpf.base.ActionResult;
import jnpf.exception.LoginException;
import jnpf.granter.TokenGranter;
import jnpf.granter.TokenGranterBuilder;
import jnpf.model.login.LoginVO;
import jnpf.service.AuthService;
import jnpf.util.TenantProvider;
import jnpf.util.UserProvider;
import jnpf.util.LoginHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * 登录与退出服务 其他服务调用
 */
@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private TokenGranterBuilder tokenGranterBuilder;

    /**
     * 登录
     * @param parameters {grant_type}
     * @return
     * @throws LoginException
     */
    @Override
    public ActionResult<LoginVO> login(Map<String, String> parameters) throws LoginException{
        TokenGranter tokenGranter = tokenGranterBuilder.getGranter(parameters.getOrDefault("grant_type", ""));
        ActionResult<LoginVO> result;
        try {
            result = tokenGranter.granter(parameters);
        }catch (Exception e){
            if(!(e instanceof LoginException)){
                String msg = e.getMessage();
                if(msg == null){
                    msg = "登录异常";
                }
                throw new LoginException(msg);
            }
            throw e;
        }finally{
            LoginHolder.clearUserEntity();
            TenantProvider.clearBaseSystemIfo();
        }
        return result;
    }


    /**
     * 踢出用户, 用户将收到Websocket下线通知
     * 执行流程：认证服务退出用户->用户踢出监听->消息服务发送Websocket推送退出消息
     * @param tokens
     */
    @Override
    public ActionResult kickoutByToken(String... tokens){
        UserProvider.kickoutByToken(tokens);
        return ActionResult.success();
    }

    /**
     * 踢出用户, 用户将收到Websocket下线通知
     * 执行流程：认证服务退出用户->用户踢出监听->消息服务发送Websocket推送退出消息
     * @param userId
     * @param tenantId
     */
    @Override
    public ActionResult kickoutByUserId(String userId, String tenantId){
        UserProvider.kickoutByUserId(userId, tenantId);
        return ActionResult.success();
    }
}
